package com.mingtu.guards.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.R2;
import com.mingtu.center.activity.ResourceRecordActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.videocompress.VideoCompress;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.common.view.MultiGridView;
import com.mingtu.guards.R;
import com.mingtu.uploadevent.adapter.UploadPictureVideoAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.uploadevent.bean.UploadFileResultBean;
import com.mingtu.uploadevent.callback.UploadCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

public class PostingActivity extends MyBaseActivity {

    @BindView(R2.id.edit_name)
    ContainsEmojiEditText editName;
    @BindView(R2.id.edit_describe)
    ContainsEmojiEditText editDescribe;
    @BindView(R2.id.tv_total_text_count)
    TextView tvTotalTextCount;
    @BindView(R2.id.mgv_picture_video)
    MultiGridView mgvPictureVideo;
    @BindView(R2.id.tvAddress)
    TextView tvAddress;
    @BindView(R2.id.but_submit)
    Button butSubmit;
    private int totalTextCount = 200;
    private String address;
    private String lat;
    private String lng;
    private UploadPictureVideoAdapter uploadPictureVideoAdapter;
    private int maxSelecNum = 1;
    private ArrayList<HashMap<String, Object>> mylist;
    public ArrayList<LinkedHashMap<String, Object>> picVideoArray = new ArrayList<>();
    private LinkedHashMap<String, Object> picVidoInfo = new LinkedHashMap<>();
    private final int UPLOAD_TYPE_IMG = 1;
    private final int UPLOAD_TYPE_VIDEO = 3;
    private String describe;
    private String name;
    private AMap aMap;
    private MapView mapView;
    private List<Marker> markers = new ArrayList<>();
    private int textNum = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_posting;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("资源采集");
        editDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textNum -= count;
                tvTotalTextCount.setText((totalTextCount - textNum) + "");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textNum += count;
                tvTotalTextCount.setText((totalTextCount - textNum) + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
                MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                String str = MyUtills.getEditText(editDescribe);
                editDescribe.setSelection(str.length());
            }
        });

    }

    @Override
    protected void initData() {
        address = SPStaticUtils.getString(SPTools.address);
        lat = SPStaticUtils.getString(SPTools.lat);
        lng = SPStaticUtils.getString(SPTools.lng);
        tvAddress.setText(address);
        tvTotalTextCount.setText(totalTextCount + "");

        if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
            LatLng location = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.center.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markers.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }

        int screenWidth = ScreenUtils.getScreenWidth(); //照片一行3个，间隙是10dp 左右边距是10dp
        int mWidth = (screenWidth - SizeUtils.dp2px(5) * 2 - SizeUtils.dp2px(15) * 4) / 3;
        uploadPictureVideoAdapter = new UploadPictureVideoAdapter(context);
        uploadPictureVideoAdapter.setItemWidth(mWidth);
        mgvPictureVideo.setAdapter(uploadPictureVideoAdapter);
        uploadPictureVideoAdapter.setOnItemClickListener(picVideoOnItemClickListener);
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(com.mingtu.center.R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
    }

    @Override
    protected void getData() {

    }

    @Override
    protected void onClickTitlebarRightText(View view) {
        super.onClickTitlebarRightText(view);

        IntentUtils.getInstance().readyGo(PostingActivity.this, ResourceRecordActivity.class);

    }


    @OnClick(R2.id.but_submit)
    public void onViewClicked(View v) {
        if (v.getId() == com.mingtu.center.R.id.but_submit) {
            name = UIUtils.getEditText(editName);
            describe = UIUtils.getEditText(editDescribe);
            if (StringUtils.isEmpty(name)) {
                ToastUtils.showLong("请输入物种名称");
                return;
            }
            if (StringUtils.isEmpty(describe)) {
                ToastUtils.showLong("请输入您看到的情况");
                return;
            }

            mylist = new ArrayList<>();
            mylist.addAll(picVideoArray);

            if (mylist.size() == 0) {
                ToastUtils.showLong("请上传视频、图片相关文件！");
                return;
            }
            //上报
            uploadEvent();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //每次进来清空数据，重新上传
        try {
            picVidoInfo.clear();
            picVideoArray.clear();

            //销毁地图对象
            if (aMap != null) {
                mapView.onDestroy();
            }

            for (Marker marker : markers) {
                marker.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传图片、视频的点击事件
     */
    public UploadPictureVideoAdapter.OnItemClickListener picVideoOnItemClickListener = new UploadPictureVideoAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            KeyboardUtils.hideSoftInput(PostingActivity.this);
            int id = view.getId();
            if (id == com.mingtu.center.R.id.iv_delete) {//删除操作
                picVideoArray.remove(position);
                uploadPictureVideoAdapter.removeData(position);
            } else if (id == com.mingtu.center.R.id.raiv_place) {//添加图片、视频操作、
                BaseApplication.initPhotoSelector(1, false).forResult(new MyResultCallback());
            } else if (id == com.mingtu.center.R.id.raiv_img) {//预览操作
                ArrayList<LocalMedia> localMediaList = uploadPictureVideoAdapter.getData();
                if (localMediaList.size() > 0) {
                    BaseApplication.initPreviewModel().startActivityPreview(position, false, localMediaList);

                }
            }
        }
    };

    /**
     * 返回结果回调
     */
    private class MyResultCallback implements OnResultCallbackListener<LocalMedia> {

        private ArrayList<LocalMedia> result;

        @Override
        public void onResult(final ArrayList<LocalMedia> result) {
            try {
                this.result = result;
                if (result != null) {
                    for (LocalMedia media : result) {

                        String mimeType = media.getMimeType();
                        if (PictureMimeType.isHasVideo(mimeType)) {
                            //视频时，独立获取path,androidQ时候，需要兼容，  path 含有content字段 需要使用 realth 里的路径
                            String strCompress = "";
                            String strPath = "";
                            if (media.getPath().indexOf("content:") != -1) {
                                String videoPath = media.getRealPath();
                                strCompress = videoPath.substring(0, videoPath.indexOf(".")) + "compress.mp4";
                                strPath = media.getRealPath();
                            } else {
                                String videoPath = media.getPath();
                                strCompress = videoPath.substring(0, videoPath.indexOf(".")) + "compress.mp4";
                                strPath = media.getPath();
                            }

                            File file = new File(strPath);
                            MyLogUtil.e("File", "压缩前==" + FileUtils.getSize(file));
                            media.setCompressPath(strCompress);
                            VideoCompress.compressVideoLow(strPath, strCompress, new MyCompressListener(media, result)); //压缩视频后，上传视频换取url

                        } else if (PictureMimeType.isHasImage(mimeType)) {
                            String path = media.getAvailablePath();
                            //图片
                            ArrayList<File> files = new ArrayList<>();
                            File file = new File(path);
                            files.add(file);
                            uploadFile(files, new UploadCallback() {
                                @Override
                                public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                                    if (urlBeans != null) {
                                        int size = urlBeans.size();
                                        if (size > 0) {
                                            for (int i = 0; i < size; i++) {
                                                String url = urlBeans.get(i).getUrl();
                                                picVidoInfo = new LinkedHashMap<>();
                                                picVidoInfo.put("type", UPLOAD_TYPE_IMG);
                                                picVidoInfo.put("url", url);
                                                picVideoArray.add(picVidoInfo);
                                            }
                                        }
                                    }

                                    uploadPictureVideoAdapter.upData(result); //更新显示
                                }
                            });
                        }


                    }


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onCancel() {
            Log.i("test", "PictureSelector Cancel");
        }
    }


    /**
     * 压缩监听事件
     */
    private class MyCompressListener implements VideoCompress.CompressListener {
        public LocalMedia media;
        public ArrayList<LocalMedia> result;

        public MyCompressListener(LocalMedia media, ArrayList<LocalMedia> result) {
            this.media = media;
            this.result = result;
        }

        @Override
        public void onStart() {
            showLoadingDialog();
        }

        @Override
        public void onSuccess() {

            hideLoadingDialog();

            String commpressPath = media.getCompressPath();
            File compressFile = new File(commpressPath);
            ArrayList<File> files = new ArrayList<>();
            files.add(compressFile);

            MyLogUtil.e("File", "压缩后==" + FileUtils.getSize(compressFile));

            uploadFile(files, new UploadCallback() {
                @Override
                public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                    if (urlBeans != null) {
                        int size = urlBeans.size();
                        if (size > 0) {
                            for (int i = 0; i < size; i++) {
                                String url = urlBeans.get(i).getUrl();
                                if (!StringUtils.isEmpty(url)) {
                                    picVidoInfo = new LinkedHashMap<>();
                                    picVidoInfo.put("type", UPLOAD_TYPE_VIDEO);
                                    picVidoInfo.put("url", url);
                                    picVideoArray.add(picVidoInfo);

                                } else {
                                    ToastUtils.showLong("视频过大，请选择小一些的视频文件");
                                }

                            }
                        }
                    }
                    uploadPictureVideoAdapter.upData(result); //更新显示
                }
            });
        }

        @Override
        public void onFail() {

        }

        @Override
        public void onProgress(float percent) {

        }
    }

    /**
     * 上传图片、视频(目前接口只支持单张上传，要支持多张上传的话需要更改逻辑)
     */
    private void uploadFile(ArrayList<File> files, final UploadCallback uploadCallback) {

        OkGo.<String>post(Constant.getInstance().POST_UPLOAD_FILE)
                .tag(this)
                .addFileParams("files", files)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            UploadFileResultBean resultBean = new UploadFileResultBean();
                            resultBean = gson.fromJson(result, UploadFileResultBean.class);
                            List<UploadFileResultBean.DataBean.UrlBean> urlBeans = resultBean.getData().getUrl();
                            uploadCallback.result(urlBeans);
                        } else {
                            uploadCallback.result(null);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 上报事件
     */
    private void uploadEvent() {
        butSubmit.setEnabled(false);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("address", address);
        hashMap.put("memo", describe);
        hashMap.put("name", name);
        hashMap.put("lat", lat);
        hashMap.put("lng", lng);
        hashMap.put("speciesInfoAttachEntityList", mylist);
        String str = GsonUtils.toJson(hashMap);


        OkGo.<String>post(Constant.getInstance().POST_SPECIES_INFO)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String success = jsonObject.getString("success");
                            if (success.indexOf("ok") != -1) {
                                ToastUtils.showLong("提交成功！");
                                butSubmit.setEnabled(true);
                                //实例化Timer类 ,守护线程，不在后台一直运行
                                ActivityUtil.removeActivity(PostingActivity.this);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        butSubmit.setEnabled(true);
                    }
                });
    }


}